import * as path from 'path';
import * as program from 'commander';
import * as fs from 'fs-extra';
import { initConfig, generateHock, syncHock, diff } from './index';

// 获取版本号
const packageFilePath = path.join(__dirname, '..', 'package.json');
const packageInfo = JSON.parse(fs.readFileSync(packageFilePath, 'utf8'));
const currentVersion = packageInfo.version;
const PROJECT_ROOT = process.cwd();

const config = {
  "origins": [
    {
      "originUrl": "",
      "name": ""
    }
  ],
  "outDir": "/src/service",
  "servicesHeader": "mport BaseService from './base';"
};

program
  .version(currentVersion, '-v, --version').usage('[命令] [配置项]');

(async () => {

  function init() {
    const filePath = path.join(PROJECT_ROOT, 'snippets-config.json');
    const existsFile = fs.existsSync(filePath);
    if (!existsFile) {
      console.log(`请先添加snippets-config.json文件，可通过init命令来初始化`)
      return true;
    }
    initConfig(filePath, PROJECT_ROOT);
  }

  program
    .command('init')
    .description('初始化配置')
    .action((): void => {
      const filePath = path.join(PROJECT_ROOT, 'snippets-config.json');
      const existsFile = fs.existsSync(filePath);
      if (existsFile) {
        console.log(`已存在snippets-config.json文件`)
        return;
      }
      fs.outputJson(`${PROJECT_ROOT}/snippets-config.json`, config, { spaces: 2 }, err => {
        if (err) {
          return console.error(err)
        };
        console.log(`初始化配置${PROJECT_ROOT}/snippets-config.json成功`);
      });
    });
  program
    .command('sync')
    .description('同步代码')
    .action(async () => {
      if (init()) {
        return;
      };
      await syncHock();
      const diffs = diff();
      diffs.map(item => {
        console.log(item.origins);
        const list = item.list;
        list.map(el => {
          console.log(`${el.label} ${el.description}`);
        })
      })
    });
  program
    .command('generate')
    .description('生成代码')
    .action(() => {
      if (init()) {
        return;
      };
      generateHock();
    });
})();

program.parse(process.argv);
